package org.summer.lawyer.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.summer.common.core.exception.ServiceException;
import org.summer.common.core.utils.MapstructUtils;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.common.satoken.utils.LoginHelper;
import org.summer.lawyer.domain.LegalCase;
import org.summer.lawyer.domain.bo.legalcase.LegalCaseBo;
import org.summer.lawyer.domain.vo.legalcase.LegalCaseUpdateVo;
import org.summer.lawyer.domain.vo.legalcase.LegalCaseVo;
import org.summer.lawyer.mapper.LegalCaseMapper;
import org.summer.lawyer.service.ILawyerInfoService;
import org.summer.lawyer.service.ILegalCaseService;
import org.summer.lawyer.service.IWxUserService;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LegalCaseServiceImpl extends ServiceImpl<LegalCaseMapper, LegalCase> implements ILegalCaseService {

    private final IWxUserService wxUserService;

    private final ILawyerInfoService lawyerInfoService;


    @Override
    public TableDataInfo<LegalCaseVo> selectListByScope(LegalCaseVo vo) {
        LambdaQueryWrapper<LegalCase> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(vo.getLawFirmId() != null, LegalCase::getLawFirmId, vo.getLawFirmId())
                .eq(vo.getLawyerId() != null, LegalCase::getLawyerId, vo.getLawyerId())
                .orderByDesc(LegalCase::getId);
        return TableDataInfo.build(baseMapper.selectVoList(queryWrapper));
    }


    @Override
    public void updateLegalCase(LegalCaseUpdateVo vo) {
        LegalCase legalCase = baseMapper.selectById(vo.getId());
        if (ObjectUtil.isNull(legalCase)) {
            throw new ServiceException("未找到对象信息");
        }
        LambdaUpdateWrapper<LegalCase> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(LegalCase::getId, vo.getId())
                .set(LegalCase::getTitle, vo.getTitle())
                .set(LegalCase::getCaseContent, vo.getCaseContent())
                .set(LegalCase::getCaseImage, vo.getCaseImage());
        baseMapper.update(updateWrapper);
    }

    @DSTransactional(rollbackFor = Exception.class)
    @Override
    public void deleteLegalCaseByIds(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            throw new ServiceException("主键不能为空");
        }
        this.removeByIds(ids);
    }

    /**
     * 查询法律案例
     *
     * @param id 主键
     * @return 法律案例
     */
    @Override
    public LegalCaseVo selectLegalCaseVoById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询法律案例列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 法律案例分页列表
     */
    @Override
    public TableDataInfo<LegalCaseVo> selectPageList(LegalCaseBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<LegalCase> lqw = buildQueryWrapper(bo);
        Page<LegalCaseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的法律案例列表
     *
     * @param bo 查询条件
     * @return 法律案例列表
     */
    @Override
    public List<LegalCaseVo> selectLegalCaseVoList(LegalCaseBo bo) {
        LambdaQueryWrapper<LegalCase> lqw = Wrappers.lambdaQuery();
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<LegalCase> buildQueryWrapper(LegalCaseBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<LegalCase> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getCaseScope()), LegalCase::getCaseScope, bo.getCaseScope());
        lqw.eq(StrUtil.isNotBlank(bo.getTitle()), LegalCase::getTitle, bo.getTitle());
        lqw.eq(StrUtil.isNotBlank(bo.getCaseImage()), LegalCase::getCaseImage, bo.getCaseImage());
        lqw.eq(bo.getLawFirmId() != null, LegalCase::getLawFirmId, bo.getLawFirmId());
        lqw.eq(bo.getLawyerId() != null, LegalCase::getLawyerId, bo.getLawyerId());
        lqw.eq(StrUtil.isNotBlank(bo.getCaseContent()), LegalCase::getCaseContent, bo.getCaseContent());
        return lqw;
    }

    /**
     * 新增法律案例
     *
     * @param bo 法律案例
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(LegalCaseBo bo) {
        LegalCase add = MapstructUtils.convert(bo, LegalCase.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtil.date());
        add.setUpdateTime(DateUtil.date());
        if(LoginHelper.getLoginUser() != null){
            add.setCreateBy(LoginHelper.getUserId());
            add.setUpdateBy(LoginHelper.getUserId());
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改法律案例
     *
     * @param bo 法律案例
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(LegalCaseBo bo) {
        LegalCase update = MapstructUtils.convert(bo, LegalCase.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtil.date());
        if(LoginHelper.getLoginUser() != null){
            update.setUpdateBy(LoginHelper.getUserId());
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(LegalCase entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除法律案例信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void saveLegalCase(LegalCaseBo bo) {
        if (bo.getId() == null) {
            insertByBo(bo);
        } else {
            updateByBo(bo);
        }
    }
}
